package com.scs.application.modules.upms.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.CacheConsts;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 */
@Slf4j
@Component
public class InitCacheListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private UserService userService;

    private volatile boolean inited;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (inited) {
            return;
        }
        String displayName = event.getApplicationContext().getDisplayName();
        if (displayName.contains("zipkin") || displayName.startsWith("FeignContext")) {
            return;
        }

        log.info("系统初始化缓存开始......");
//        initUserCache();

        log.info("系统初始化缓存结束......");
        inited = true;
    }

    private void initUserCache() {
        log.info("用户信息初始化缓存开始......");

        List<User> list = userService.list(Wrappers.<User>query().select("id,nickname,login_key").gt("gmt_last_login", DateUtils.addDays(new Date(), -30)));
        for (User user : list) {
            CacheUtils.put(CacheConsts.UPMS_USERS_ID, user.getId(), user);
        }
        log.info("用户信息初始化缓存结束，共加载{}个用户......", list.size());

    }
}
